package com.example.music;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;

import com.example.lwx.R;

public class BindServiceActivity extends Activity implements View.OnClickListener {

    Button bt_start;
    Button bt_callFunc;
    Button bt_stop;

    ServiceConnection conn;
    BindService.MyBinder myBind;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bindservice);
        bt_start=findViewById(R.id.start);
        bt_callFunc=findViewById(R.id.callFunc);
        bt_stop=findViewById(R.id.stop);
        bt_start.setOnClickListener(this);
        bt_callFunc.setOnClickListener(this);
        bt_stop.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.start){
            if(conn==null){
                conn=new ServiceConnection() {
                    @Override
                    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                        myBind=(BindService.MyBinder)iBinder;
                    }

                    @Override
                    public void onServiceDisconnected(ComponentName componentName) {

                    }
                };
                Intent intent= new Intent(BindServiceActivity.this,BindService.class);
                bindService(intent,conn,BIND_AUTO_CREATE);
            }
        }
        if(view.getId()==R.id.callFunc){
            myBind.callFun();
        }
        if(view.getId()==R.id.stop){
            if(conn!=null){
                unbindService(conn);
                conn=null;
            }
        }
    }
}
